<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use DB;

class userController extends Controller
{
    //用户表信息
    public function index(Request $request)
    {
        // 保存搜索的条件
        $where = [];
        $db = DB::table('storeuser');
        if($request->has('userName')){
            $db->where('userName','like',"%{$request->input('userName')}%");
            $where['userName'] = $request->input('userName');
        }
        if($request->has('userSex')){
            $db->where('userSex',$request->input('userSex'));
            $where['userSex'] = $request->input('userSex');
        }
        $list = $db->paginate(3);
        
        return view('admin.userManager',['list'=>$list,'where'=>$where]);
    }

    public function create()
    {
    	return view('admin.userAdd');
    }

    public function store(Request $request)
    {
        //自定义错误信息
        $message = [
            'required' => ':attribute 的字段是必须的',
            'between' => ':attribute 字段的值必须在:min - :max',
            'unique' => ':attribute 字段值已存在!',
            'digits' => ':attribute 字段值必须为数值且长度为11',
        ];
        //设定验证规则
        $this->validate($request, [
            'userName' => 'required|unique:storeuser',
            'userPass' => 'required|between:6,12',
            'userTel' => 'required|digits:11',
            'userEmail' => 'required',
        ],$message);
    	$data = $request->except('_token');
    	$row = DB::table('storeuser')->insert($data);
    	if($row>0){
    		return redirect('/admin/userManager')->with('msg','添加成功');
    	}
    }

    public function edit($userId)
    {
    	$value = DB::table('storeuser')->where('userId',$userId)->first();
    	return view('admin.userEdit',['v'=>$value]);
    }

    public function update($userId,Request $request)
    {
        //自定义错误信息
        $message = [
            'required' => ':attribute 的字段是必须的',
            'between' => ':attribute 字段的值必须在:min - :max',
            'unique' => ':attribute 字段值已存在!',
            'digits' => ':attribute 字段值必须为数值且长度为11',
        ];
        //设定验证规则
        $this->validate($request, [
            'userPass' => 'required|between:6,12',
            'userTel' => 'required|digits:11',
            'userEmail' => 'required',
        ],$message);

    	// 获取除了指定字段，剩下的字段
    	$data = $request->except('_token','_method','name');

        $data['userPass'] = md5($data['userPass']);

    	$row = DB::table('storeuser')->where('userId',$userId)->update($data);
    	if($row>0){
    		return redirect('/admin/userManager')->with('msg','修改成功');
    	}
    }

    public function destroy($userId)
    {
    	$row = DB::table('storeuser')->where('userId',$userId)->delete();
    	if($row>0){
            return redirect('/admin/userManager')->with('msg','删除成功');
    	}
    }
}
